package runnerservice

import (
	"fmt"
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/manager"
	"gmap-backend/internal/server/vo"
	"gmap-backend/internal/util/pathutil"
	"strings"
)

// OpenCmdWithWorkDir 以指定目录为工作目录打开命令提示符
func OpenCmdWithWorkDir(appConfig *config.AppConfig, req *vo.PathReq, bins [][]byte) *vo.BaseActionResp {
	parsePathResult := pathutil.ParseValidPath(req.Path, req.CtxDir)
	if !parsePathResult.Succ {
		panic(fmt.Sprintf("指定的路径不存在：\r\n%s", req.Path))
	}
	if parsePathResult.Succ && parsePathResult.File {
		panic(fmt.Sprintf("不支持对文件执行此操作：\r\n%s", parsePathResult.ValidPath))
	}
	batPath := manager.SaveCmdFile(appConfig, "", "", true)
	manager.Cmd_C(batPath, parsePathResult.ValidPath)
	return &vo.BaseActionResp{}
}

// 执行脚本
func ExecShell(appConfig *config.AppConfig, req *vo.CmdRunReq, bins [][]byte) *vo.BaseActionResp {
	return execShellInner(appConfig, req, false)
}

// 使用start命令执行脚本
func ExecShellStart(appConfig *config.AppConfig, req *vo.CmdRunReq, bins [][]byte) *vo.BaseActionResp {
	return execShellInner(appConfig, req, true)
}

func execShellInner(appConfig *config.AppConfig, req *vo.CmdRunReq, useStart bool) *vo.BaseActionResp {
	// 统一使用utf-8 code page，即65001
	cmd := ""
	if useStart {
		lines := strings.Split(strings.ReplaceAll(strings.TrimSpace(req.Cmd), " \\", "\n"), "\n")
		if len(lines) >= 2 {
			panic("start执行方式不支持多行命令")
		}
		cmd += `start "gmap-cmd" `
	}
	cmd += strings.ReplaceAll(req.Cmd, " \\", "\n") + "\n"
	if !useStart {
		if req.Pause {
			cmd += "pause\n"
		}
		if !req.Pause && req.ExitTimeout > 0 {
			cmd += fmt.Sprintf("timeout /t %v", req.ExitTimeout) + "\n"
		}
	} else {
		cmd += "timeout /t 1\n"
	}
	cmd += "exit\n"

	batPath := manager.SaveCmdFile(appConfig, cmd, "", true)
	manager.Cmd_C(batPath, "")
	return &vo.BaseActionResp{}
}
